package cqie.personal.frame.interceptor;


import cqie.personal.frame.config.RequiredPermission;
import cqie.personal.frame.entity.UserInfo;
import cqie.personal.frame.enums.Code;
import cqie.personal.frame.exception.PermissionException;
import cqie.personal.frame.service.UserInfoService;
import cqie.personal.frame.util.JwtUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PermissionInterceptor implements HandlerInterceptor {

    @Resource
    UserInfoService service;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws PermissionException {
        String token  = request.getHeader("token");
        UserInfo user = JwtUtil.parsingToken(token);
        return this.hasPermission(handler, user.getUid());
    }

    private boolean hasPermission(Object handler, Integer UID) throws PermissionException {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequiredPermission requiredPermission = handlerMethod.getMethod().getAnnotation(RequiredPermission.class);
        if (requiredPermission == null) {
            requiredPermission = handlerMethod.getMethod().getDeclaringClass().getAnnotation(RequiredPermission.class);
        }
        if (requiredPermission != null){
           Integer  userPermission = service.getUserPermission(UID);
            if (userPermission == null||userPermission<requiredPermission.value()) {
                System.out.println("拦截未授权用户 : " + UID + " , 尝试使用未拥有权限 : " + requiredPermission.value() + " ");
                throw new PermissionException(Code.ACCESS_DENIED.getMessage());
            }
        }
        return true;
    }
}


